using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using umbraco;
using umbraco.cms.businesslogic.web;
using System.Xml;
using System.IO;
using System.Globalization;
using System.Text;

namespace Nibble.AlphabetFolder
{
    public partial class AlphabetFolderInstall : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DocumentType byAlias = DocumentType.GetByAlias("AlphabetFolder");
            foreach (DocumentType type2 in DocumentType.GetAll)
            {
                if (type2.Alias != "AlphabetFolder")
                {
                    CheckBox child = new CheckBox();
                    child.ID = type2.Alias;
                    child.Text = type2.Alias;
                    child.AutoPostBack = true;
                    child.CheckedChanged += new EventHandler(this.box_CheckedChanged);
                    this.Panel3.Controls.Add(child);
                    Literal literal = new Literal();
                    literal.Text = "<br/>";
                    this.Panel3.Controls.Add(literal);
                }
            }

        }

        protected void box_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox box = (CheckBox)sender;
            if (Session["AlphabetFolderInstall"] == null)
            {
                ArrayList list = new ArrayList();
                if (box.Checked)
                {
                    list.Add(box.Text);
                }
                else
                {
                    list.Remove(box.Text);
                }
                Session["AlphabetFolderInstall"] = list;
            }
            else if (box.Checked)
            {
                ((ArrayList)Session["AlphabetFolderInstall"]).Add(box.Text);
            }
            else
            {
                ((ArrayList)Session["AlphabetFolderInstall"]).Remove(box.Text);
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            DocumentType byAlias = DocumentType.GetByAlias("AlphabetFolder");
            if (base.Session["AlphabetFolderInstall"] != null)
            {
                for (int i = 0; i < ((ArrayList)Session["AlphabetFolderInstall"]).Count; i++)
                {
                    string alias = ((ArrayList)Session["AlphabetFolderInstall"])[i].ToString();
                    DocumentType type2 = DocumentType.GetByAlias(alias);
                    bool flag = true;
                    int[] numArray = new int[byAlias.AllowedChildContentTypeIDs.Length + 1];
                    int index = 0;
                    while (index < byAlias.AllowedChildContentTypeIDs.Length)
                    {
                        numArray[index] = (int)byAlias.AllowedChildContentTypeIDs.GetValue(index);
                        if (((int)byAlias.AllowedChildContentTypeIDs.GetValue(index)) == type2.Id)
                        {
                            flag = false;
                        }
                        index++;
                    }
                    numArray[byAlias.AllowedChildContentTypeIDs.Length] = type2.Id;
                    if (flag)
                    {
                        byAlias.AllowedChildContentTypeIDs = numArray;
                    }


                    foreach (DocumentType type3 in DocumentType.GetAll)
                    {
                        foreach (int num3 in type3.AllowedChildContentTypeIDs)
                        {
                            if ((num3 == type2.Id) && (type3.Alias != "AlphabetFolder"))
                            {
                                bool flag2 = true;
                                int[] numArray2 = new int[type3.AllowedChildContentTypeIDs.Length + 1];
                                for (index = 0; index < type3.AllowedChildContentTypeIDs.Length; index++)
                                {
                                    numArray2[index] = (int)type3.AllowedChildContentTypeIDs.GetValue(index);
                                    if (((int)type3.AllowedChildContentTypeIDs.GetValue(index)) == byAlias.Id)
                                    {
                                        flag2 = false;
                                    }
                                }
                                numArray2[type3.AllowedChildContentTypeIDs.Length] = byAlias.Id;
                                if (flag2)
                                {
                                    type3.AllowedChildContentTypeIDs = numArray2;
                                }
                            }
                        }
                    }
                    XmlDocument xd = new XmlDocument();
                    xd.Load(HttpContext.Current.Server.MapPath("/config/Nibble.AlphabetFolder/AlphabetFolder.config"));
                    xd.SelectSingleNode("AlphabetFolder").AppendChild(xmlHelper.addTextNode(xd, "DocumentTypeAlias", alias));
                    FileStream stream = File.Open(HttpContext.Current.Server.MapPath("/config/Nibble.AlphabetFolder/AlphabetFolder.config"), FileMode.Create);
                    StreamWriter writer = new StreamWriter(stream);
                    writer.WriteLine(xd.OuterXml);
                    writer.Close();
                    stream.Close();
                    if (this.cbMove.Checked)
                    {
                        foreach (Document document2 in Document.GetRootDocuments())
                        {
                            if (document2.HasChildren)
                            {
                                this.loopchildren(document2, alias);
                            }
                        }
                    }
                }
                this.Panel1.Visible = false;
                this.Panel2.Visible = true;
            }
        }

        private void loopchildren(Document ParentDocument, string alias)
        {
            foreach (Document document in ParentDocument.Children)
            {
                if (document.Id > 0)
                {
                    if (document.ContentType.Alias == alias)
                    {
                        this.Move(document);
                    }
                    if (document.HasChildren)
                    {
                        this.loopchildren(document, alias);
                    }
                }
            }
        }


        private void Move(Document documentObject)
        {
            if (new Document(documentObject.Parent.Id).ContentType.Alias != "AlphabetFolder")
            {
                char firstChar = Convert.ToChar(RemoveDiacritics(documentObject.Text).Substring(0, 1).ToLower());

                string folderName = "-";

                if (Char.IsLetter(firstChar))
                {
                    folderName = firstChar.ToString();
                }

                Document document = null;

                
                foreach (Document aFolder in new Document(documentObject.Parent.Id).Children)
                {
                    if (aFolder.Text == folderName)
                    {
                        document = new Document(aFolder.Id);
                        break;
                    }
                }
                if (document == null)
                {
                    document = Document.MakeNew(folderName, DocumentType.GetByAlias("AlphabetFolder"), documentObject.User, documentObject.Parent.Id);
                    document.Publish(documentObject.User);
                    library.PublishSingleNode(document.Id);
                }

                documentObject.Move(document.Id);
                
            }
        }

        private string RemoveDiacritics(String s)
        {
            String normalizedString = s.Normalize(NormalizationForm.FormD);
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < normalizedString.Length; i++)
            {
                Char c = normalizedString[i];
                if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
                    stringBuilder.Append(c);
            }

            return stringBuilder.ToString();
        } 

    }
}